package com.wisdytech.linkdcs.linkdcsservicepad.common.handler;

import com.alibaba.fastjson.JSON;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.linkdcs.linkdcsservicepad.common.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <p>ClassName: ExceptionHandler</p>
 * <p>Description: 异常处理类</p>
 * <p>Author: PC</p>
 * <p>Date: 2017-10-17</p>
 */
@ControllerAdvice 
public class GlobalExceptionHandler {
    
    private Logger logger =LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /*@Resource
    private ISysLogService sysLogService;*/
    

    @ExceptionHandler
    @ResponseBody
    public Object resolveException(HttpServletRequest request, HttpServletResponse response,
            Exception ex) {
        logger.error("系统异常",ex);
       /* //获取用户信息
        SysUser user = BaseUtil.getCurrentUser();
        //保存异常信息
        addSystemException(user, request, ex);*/
        
        //判断是否是ajax请求
        boolean isAjax =isAjax(request);
        
        if(isAjax){
            String errorMessge = "系统异常";
            String errorResponse="";
            
            if(ex instanceof ServiceException) {
                errorMessge = ex.getMessage();
                errorResponse =JSON.toJSONString(StandardResult.getFailResult(errorMessge));
            }else{
            	errorResponse =JSON.toJSONString(StandardResult.getFailResult(errorMessge));
            }
            
            return errorResponse;      
        }else{
            return new ModelAndView("redirect:/error");
        }
    }
    
    /**
     * 
     * <p>Description: 判断是否为ajax请求</p>
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request){
    	return true;
        /*if(StringUtils.isBlank(request.getHeader("X-Requested-With"))){
            return false;
        }
        return  "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()) ;*/
    }
    
    
    
    
    
}
